package com.chat.client;

import com.alibaba.fastjson.JSON;
import com.chat.entity.Message;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.util.Scanner;

public class WsClient2 {

    //  运行处理消息服务器WsServer主机的URL
    private static String wsServerURL = "ws://localhost:6666/";


    public static void main(String[] args) throws Exception {
        Scanner sc = new Scanner(System.in);

        String name;
        WebSocketClient client;
        while (true){
            // 获取用户身份   ( 不同用户的名字不能一样 )
            System.out.print("请输入你的名字： ");
            name = sc.next();

            //  建立连接
            client = new WebSocketClient(new URI(wsServerURL+name)) {
                @Override
                public void onOpen(ServerHandshake serverHandshake) {
                    System.out.println("客户端与服务端建立连接");
                }

                @Override
                public void onMessage(String s) {
                    Message message = JSON.parseObject(s, Message.class);
                    System.out.println("\n" + message.getSender() + ": " + message.getContent());
                }

                @Override
                public void onClose(int i, String s, boolean b) {
                    System.out.println("客户端与服务端断开连接");
                    System.exit(0);
                }

                @Override
                public void onError(Exception e) {
                    System.out.println("服务端发生错误");
                }
            };
            client.connect();
            Thread.sleep(1000);
            if (client.isOpen()){
                break;
            }
        }

        Message message = new Message();
        message.setSender(name);
        while (true){

           String toUser = sc.next();
           String content = sc.nextLine();
           message.setReceiver(toUser);
           message.setContent(content);

           client.send(JSON.toJSONString(message));
        }
    }
}
